package com.vf.cloud.pass.mvc.biz.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.types.Binary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.jfinal.kit.StrKit;
import com.vf.cloud.pass.common.datasource.annotation.Tx;
import com.vf.cloud.pass.common.domain.sys.DocApi;
import com.vf.cloud.pass.common.domain.sys.DocApiFile;
import com.vf.cloud.pass.common.repository.base.Thumbnail;
import com.vf.cloud.pass.common.util.R;
import com.vf.cloud.pass.common.util.UuidUtil;
import com.vf.cloud.pass.mvc.biz.service.IThumbnail;

import lombok.RequiredArgsConstructor;


@RequiredArgsConstructor
@RestController
@RequestMapping("/API")
public class APIController {

	@Autowired
	private IThumbnail thumbnailImpl;
	
	@GetMapping("/findList")
	public R<List<DocApi>> findList(@RequestParam(name = "rootId") String rootId) {
		List<DocApi> docApis = DocApi.dao.getTableTree(rootId);
		return R.ok(docApis);
	}
	
	@GetMapping("/folderList")
	public R<List<DocApi>> folderList(@RequestParam(name = "type") String type) {
		List<DocApi> docApis = DocApi.dao.find("select * from "+DocApi.TABLE_NAME+" where type =?",String.format("%s-M", type));
		return R.ok(docApis);
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<DocApi> save(@RequestBody DocApi docApi) {
		try {
			if (StrKit.notBlank(docApi.getId())) {
//				docApi.setUpdateTime(DateUtil.getLocalDateTime());
				if (docApi.update()) {
					return R.ok(docApi);
				} else {
					return R.failed("更新失败！");
				}
			} else {
				if (StrKit.isBlank(docApi.getName())) {
					return R.failed("名称不可以为空！");
				}
				docApi.setId(UuidUtil.getUUID());
				//superapi.setCreateTime(DateUtil.getLocalDateTime());
				if (StrKit.isBlank(docApi.getParentId())) {
					docApi.setParentId("0");
				}
				if (docApi.save()) {
					return R.ok(docApi);
				} else {
					return R.failed("保存失败！");
				}
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	public R<String> delete(@RequestParam(name = "id") String id) throws Exception {
		try {
			List<DocApi> list = DocApi.dao.getChildrenByPid(id,"");
			if (list.size() <= 0) {
				DocApi docApi = DocApi.dao.findById(id);
				if (docApi != null) {
					if (docApi.delete()) {
						return R.ok();
					} else {
						return R.failed("删除失败！");
					}
				} else {
					return R.failed("数据不存在,请刷新后再试!");
				}
			} else {
				return R.failed("有子节点,不允许删除!");
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}
	
	@Tx
	@RequestMapping(value = "/deleteFolders", method = RequestMethod.GET)
	public R<String> deleteFolders() throws Exception {
		try {
			List<DocApi> list = DocApi.dao.find("select * from doc_api where type='M'  and id not in (select parent_id from doc_api where type='C' )");// 根据id查询孩子
			if(list.size()>0) {
				for (DocApi docApi : list) {
					docApi.delete();
				}
				return R.ok("删除成功！");
			}else {
				return R.failed("没有空目录！");
			}
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}
	
	@RequestMapping(value = "/OPEN/getEditorTree", method = RequestMethod.GET)
	public R<List<DocApi>> getEditorTree(String id,boolean isRute) {
		return R.ok(DocApi.dao.getTree("0","EDITOR"));
	}
	
	@RequestMapping(value = "/OPEN/getDocTree", method = RequestMethod.GET)
    public R<List<DocApi>> getDocTree(){
    	return R.ok(DocApi.dao.getTree("0","DOC"));
    }
	
	@RequestMapping(value = "/getTree", method = RequestMethod.GET)
    public R<List<DocApi>> getTree(){
    	return R.ok(DocApi.dao.getTree("0",""));
    }
	
	@RequestMapping(value = "/getAllTree", method = RequestMethod.GET)
    public R<Map<String, List<DocApi>>> getAllTree(){
		Map<String, List<DocApi>> res = new HashMap<String, List<DocApi>>();
		res.put("editor", DocApi.dao.getTree("0","EDITOR"));
		res.put("doc", DocApi.dao.getTree("0","DOC"));
    	return R.ok(res);
    }
	
	@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
	public R<String> uploadImage(MultipartFile file) {
		try {
			if(file==null) {
				return R.failed("参数必填！");
			}
			Thumbnail thumbnailEntity = null;
			thumbnailEntity = new Thumbnail();
			thumbnailEntity.setId(UuidUtil.getUUID());
			thumbnailEntity.setSize(file.getSize());
			thumbnailEntity.setName(file.getName());
			thumbnailEntity.setContentType(file.getContentType());
			thumbnailEntity.setUploadDate(new Date(System.currentTimeMillis()));
			thumbnailEntity.setContent(new Binary(file.getBytes()));
			thumbnailImpl.save(thumbnailEntity);
			return R.ok(thumbnailEntity.getId());
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}
	
	@Tx
	@RequestMapping(value = "/deleteImages", method = RequestMethod.GET)
	public R<String> deleteImages(@RequestParam(name = "ids") String ids) throws Exception {
		try {
			if(StrKit.isBlank(ids)) {
				return R.failed("参数必填！");
			}
			String [] idArr = ids.split(",");
			if(idArr !=null && idArr.length>0) {
				for (String string : idArr) {
					DocApiFile docApiFile = DocApiFile.dao.findById(string);
					if (docApiFile != null) {
						docApiFile.delete();
					}
				}
			}
			return R.ok();
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}
	
	@GetMapping(value = "/OPEN/thumbnail/{id}", produces = { MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE })
	@ResponseBody
	public byte[] image(@PathVariable String id) {
		byte[] data = null;
		Thumbnail thumbnail = thumbnailImpl.findById(id);
		if (thumbnail != null) {
			data = thumbnail.getContent().getData();
		}
		return data;
	}
	
}
